<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>WebSocket</title>
  </head>
  <body>
    <textarea id="message" cols="130" rows="10"></textarea>
    <button id="btn">发送消息</button>
    <script>
      // 1. 连接上WebSocket服务器(是异步的)
      const ws = new WebSocket("ws://127.0.0.1:4000");

      // 2. 监听是否连上WebSocket服务器
      ws.onopen = function () {
        console.log("连接上WebSocket服务器");
        // 3. 向WebSocket服务器发送消息
        // ws.send("hello server");
        // 4. 绑定事件，接受服务器发过来的消息
        ws.onmessage = function (e) {
          console.log(e.data);
        };
      };

      const btnEl = document.querySelector("#btn");
      const messageEl = document.querySelector("#message");
      btnEl.onclick = function () {
        ws.send(messageEl.value.trim());
      };
    </script>
  </body>
</html>
